package com.baidu.lenovo.autotest;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.widget.TextView;

import com.baidu.aip.asrwakeup3.core.util.FileUtil;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import static com.baidu.lenovo.autotest.ExcelUtil.getXlsData;


public class TextCompareActivity extends AppCompatActivity {

	private String padFirst = "a";
	private String padSecond = "b";

	ArrayList<DiffPosition> diffPosUp;
	ArrayList<DiffPosition> diffPosDown;
	int curDiffPos = 0;

    private String readFile(String name)
    {String sampleDir = "baiduTTS";
        String tmpDir = Environment.getExternalStorageDirectory().toString() + "/" + sampleDir;

        String filename =tmpDir+ "/"+name;
        File file=new File(filename);

        String content = "";
        try
        {
            InputStream stream = new FileInputStream(file);
//            InputStream stream = getResources().getAssets().open(name);
            if (stream != null)
            {
                InputStreamReader reader = new InputStreamReader(stream);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String line;
                while ((line = bufferedReader.readLine()) != null)
                {
                    content += line + "\n";
                    Log.i("zxx", content);
                }

                stream.close();
            }
        }
        catch (IOException e)
        {
            content = "";
        }

        return content;
    }
    private Map readFileMap(String name)
    {String sampleDir = "baiduTTS";
        String tmpDir = Environment.getExternalStorageDirectory().toString() + "/" + sampleDir;

        String filename =tmpDir+ "/"+name;
        File file=new File(filename);
        Map<Long, String> map = new TreeMap<Long, String>();
        String content = "";
        String regex = ";time=";
        try
        {
            InputStream stream = new FileInputStream(file);
//            InputStream stream = getResources().getAssets().open(name);
            if (stream != null)
            {
                InputStreamReader reader = new InputStreamReader(stream);
                BufferedReader bufferedReader = new BufferedReader(reader);
                String line;
                while ((line = bufferedReader.readLine()) != null)
                {
                    content += line + "\n";
                    Log.i("zxx", content);

                    String[] array = line.split(regex);
//	        int endage = Integer.parseInt(array[1]);
                    long f = Long.parseLong(array[1]);

                    map.put(f, array[0]);
                }

                stream.close();
            }
        }
        catch (IOException e)
        {
            content = "";
        }

        return map;
    }


//    private void luanchComparision()
//    {
//        if (textViewUp.getText().length() > 0 && textViewDown.getText().length() > 0)
//        {
//            StringDescription original = new StringDescription(padFirst + textViewUp.getText());
//            StringDescription comparing = new StringDescription(padSecond + textViewDown.getText());
//            HirschbergComparision comparer = new HirschbergComparision();
//            mcsContent = comparer.hirschbergAlgorithm(original, comparing);
//            diffPosUp = setDifferentTextPartToRed(mcsContent, textViewUp);
//            diffPosDown = setDifferentTextPartToRed(mcsContent, textViewDown);
//        }
//    }
ArrayList<DiffPosition> getDiffPostList(String content, String mcs)
{
    ArrayList<DiffPosition> list = new ArrayList<DiffPosition>();
    boolean diffBegin = false;
    int posContent = 0;
    int posMCS = 0;
    DiffPosition curDiff = null;

    Log.d("", "--------------------"+content);
    while (posMCS < mcs.length()) {
        Log.e("", "============content:"+content.length()+ "============msc:" +mcs.length());
        Log.e("", "============posContent:"+posContent+ "============posMCS:" +posMCS);
        if(posContent >=content.length()){
            if (diffBegin == true)
            {

                curDiff.diffEnd = posContent - 1;
            }
            break;
        }
        if (content.charAt(posContent) != mcs.charAt(posMCS)){
            Log.d("", "if    --------------------");
            if (diffBegin == false){
                diffBegin = true;
                curDiff = new DiffPosition();
                curDiff.diffBegin = posContent;
                list.add(curDiff);
            }

            posContent++;
        }else{
            Log.d("", "else    --------------------");
            if (diffBegin == true)
            {
                diffBegin = false;
                curDiff.diffEnd = posContent - 1;
            }

            posMCS++;
            posContent++;
        }
    }
    Log.d("", "--------------------list:"+ list.size());
    return list;
}

    private SpannableStringBuilder setDiffTextToRed(ArrayList<DiffPosition> l, String content)
    	{
		SpannableStringBuilder builder = new SpannableStringBuilder(content);
		for (int i = 0; i < l.size(); i++)
		{
			ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
			DiffPosition pos = l.get(i);
			builder.setSpan(redSpan, pos.diffBegin, pos.diffEnd+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		return builder;
	}

    private ArrayList<DiffPosition> setDifferentTextPartToRed(String mcs, TextView view)
    	{
		ArrayList<DiffPosition> l = getDiffPostList(view.getText().toString(), mcs);

		SpannableStringBuilder builder = setDiffTextToRed(l,view.getText().toString());

		view.setText(builder);

		return l;
	}
    public void save(String s,String file) {
        File ttsFile;
        BufferedOutputStream ttsFileBufferedOutputStream;
        String tmpDir = FileUtil.createTmpDir(this);
        String filename = file + System.currentTimeMillis()+ ".txt";
        // 保存的语音文件是 16K采样率 16bits编码 单声道 pcm文件。
        ttsFile = new File(tmpDir, filename);
        Log.i("zxx", "try to write audio file to " + ttsFile.getAbsolutePath());
        try {
            if (ttsFile.exists()) {
                ttsFile.delete();
            }
            ttsFile.createNewFile();
            // 创建FileOutputStream对象
            FileOutputStream ttsFileOutputStream = new FileOutputStream(ttsFile);
            // 创建BufferedOutputStream对象
            ttsFileBufferedOutputStream = new BufferedOutputStream(ttsFileOutputStream);
            ttsFileBufferedOutputStream.write(s.getBytes());
            ttsFileBufferedOutputStream.flush();
            ttsFileBufferedOutputStream.close();

        } catch (IOException e) {
            // 请自行做错误处理
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    private void initPermission() {
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_textcompare);
        initPermission();
//        String answerText=readFile("answer.txt");
//        String asrText=readFile("ASR.txt");

        String answerText1="";
        String asrText1="";
        Map answerMap=readFileMap("MusicPlayer.txt");
        Map asrMap=readFileMap("baiduASRResult.txt");
        List<Long> keylist =new ArrayList<>();
//        for(Long key:keylist ){
//
//        }
        //List<String> valuesList = (List<String>) map.values();
        //map.values()返回的是collection，通过arrayList的构造方法可以实现
//        List<String> valuesList = new ArrayList<String>(answerMap.values());
//        for(String str:valuesList){
//            if(str.equals("小度小度  ")){
//              answerText1+= "\n";
//            }
//            answerText1+=str;
//        }


        Set<Map.Entry<Long, String>> es = answerMap.entrySet();

        Iterator<Map.Entry<Long, String>> it = es.iterator();

        while (it.hasNext()) {

            // 返回的是封装了key和value对象的Map.Entry对象
            Map.Entry<Long, String> en = it.next();

            // 获取Map.Entry对象中封装的key和value对象
            Long key = en.getKey();
            String value = en.getValue();

            if(value.equals("小度小度  ")){
                if(!answerText1.equals("")) {
                    answerText1 += "\n";
                }
                keylist.add(key);
            }
            answerText1+=value;
        }
        Set<Map.Entry<Long, String>> asr = asrMap.entrySet();

        Iterator<Map.Entry<Long, String>> asrit = asr.iterator();
        int index=0;
        while (asrit.hasNext()) {

            // 返回的是封装了key和value对象的Map.Entry对象
            Map.Entry<Long, String> en1 = asrit.next();

            // 获取Map.Entry对象中封装的key和value对象
            Long key1 = en1.getKey();
            String value1 = en1.getValue();
            if(index==keylist.size()-1) {
                asrText1+=value1;
            }else  if(index==keylist.size()) {
                asrText1+=value1;
                break;
            }else if(key1>keylist.get(index)&&key1<keylist.get(index+1)){
                asrText1+=value1;

            }else{
                asrText1+= "\n"+value1;
                index=index+1;
            }


        }

        String  answerTexts=answerText1.replaceAll(" |\\p{P}","");//去掉空格以及标点符号
        String  asrTexts=asrText1.replaceAll(" |\\p{P}","");
        String[] anss = answerTexts.split("\n");
        Log.i("anss", anss.toString());
        Log.i("anss", Integer.toString(anss.length));
        String[] asrs = asrTexts.split("\n");
        Log.i("asrs",asrs.toString());
        Log.i("anss", Integer.toString(asrs.length));
        HirschbergComparision comparer = new HirschbergComparision();
        String mcs ="";
        int asrIndex=0;
        String[] asrsResult =new String[asrs.length];
        String[] wakeUpResult =new String[asrs.length];

        try {
            List excel = new ArrayList();
            excel = getXlsData("/sdcard/answer.xls");
            String[] keyWord = new String[excel.size()];
            Answer mAnswer;
            String regex="";
            for (int row = 0; row < excel.size(); row++) {
                mAnswer = (Answer) excel.get(row);
                keyWord[row] = ".*"+mAnswer.keyWord+".*";
                regex+= keyWord[row];
                if(row<excel.size()-1)
                    regex+="|";
                Log.i("name",mAnswer.keyWord);
            }
            Log.i("name",regex);

            for(String s : anss){
                StringDescription original = new StringDescription(padFirst + s);
                StringDescription comparing = new StringDescription(padSecond + asrs[asrIndex]);

                if(asrs[asrIndex].matches(regex)){
                    asrsResult[asrIndex]="pass";
                }else{
                    asrsResult[asrIndex]="fail";
                }
                if(asrs[asrIndex].contains("在哪")|asrsResult[asrIndex].equals("pass")){
                    wakeUpResult[asrIndex]="pass";
                }else{
                    wakeUpResult[asrIndex]="fail";
                }
                mcs+=comparer.hirschbergAlgorithm(original, comparing)+ "\n";
                asrIndex++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//
//		String mcs = comparer.hirschbergAlgorithm(original, comparing);
////		ArrayList<DiffPosition> l = getDiffPostList("明天我要去国土资源厅详谈面试", mcs);
		Log.i("mcs", mcs);
        save(mcs,"textcompareMCS");
        TextView view1 = (TextView) findViewById(R.id.textView1);

//        String content = readFile(filePath);
        view1.setText(asrTexts);
        //view1.setMovementMethod(ScrollingMovementMethod.getInstance());
        save(asrTexts,"textcompareASR");
        save(answerTexts,"textcompareANS");
//        luanchComparision();
        Log.d("", "--------------------------------------");
        diffPosUp = setDifferentTextPartToRed(mcs, view1);
        List<Order> orders = new ArrayList<Order>();
        int length =asrs.length;
        for(int i = 0;i < length;i++){
            Order order = new Order( anss[i],  asrs[i],  asrsResult[i],  wakeUpResult[i]);
            orders.add(order);
        }
        try {
            ExcelUtil.writeExcel(TextCompareActivity.this,
                    orders, "excel_ASR"+ System.currentTimeMillis());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
